package com.ruiysoft.service.order.facade;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.qiniu.util.Json;
import com.ruiysoft.controller.order.vo.OrderDeliverVo;
import com.ruiysoft.controller.order.vo.SplitOrderVO;
import com.ruiysoft.entity.logistics.LogisticsException;
import com.ruiysoft.entity.order.*;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultCode;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.logistics.ILogisticsQueryService;
import com.ruiysoft.service.order.*;
import com.ruiysoft.service.order.consts.OrderDBStatusEnum;
import net.sf.json.util.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Date : 2018/11/27
 *
 * @author WenJialu
 */
@Component
public class OrderShopFacade {

	private static Logger logger = LoggerFactory.getLogger(OrderShopFacade.class);

	@Resource
	IOrderMainService orderMainService;

    @Resource
    IOrderDetailService orderDetailService;

	@Resource
	IOrderLogisticsService orderLogisticsService;
	@Resource
	OrderPubFacade oPubFacade;
	@Resource
    IOrderReceiverInfoService orderReceiverInfoService;
	@Resource
    IOrderSkuInfoService orderSkuInfoService;
	@Resource
    IOrderSkuPicService orderSkuPicService;



	@Autowired
	ILogisticsQueryService iLogisticsQueryService;



	public IPage<OrderMain> getOrdersPage(Long shopId, Set<Integer> status, Integer pageStart, Integer pageSize) {
		if (null == shopId) {
			return new Page<OrderMain>().setRecords(Collections.emptyList());
		} else {
			return oPubFacade.getOrderMainPage(null, null, shopId, null, new ArrayList<>(status), pageStart, pageSize);
		}
	}

	public Result<Void> orderDeliver(Long shopID,OrderDeliverVo orderDeliverVo) {
		//订阅物流信息
		try {
			Result<Void> subResult = iLogisticsQueryService.subscribe(shopID, "order", orderDeliverVo.getOrderNo(), orderDeliverVo.getLogisticsNo(), orderDeliverVo.getCode());
			if(!subResult.isSuccess()){
				return subResult;
			}
			//更新主表
			OrderMain oRecord = new OrderMain();
			oRecord.setStatus(OrderDBStatusEnum.DELIVERED.getCode());
			boolean updateOM = orderMainService.update(oRecord, new QueryWrapper<OrderMain>()
					.eq("order_no", orderDeliverVo.getOrderNo())
					.in("status", OrderDBStatusEnum.PLATFORM_CONFIRMED_WAITING_FOR_SHOP_CONFIRM.getCode(), OrderDBStatusEnum.SHOP_CONFIRMED_WATTING_FOR_DELIVER.getCode())
					.eq("del_flag", false));
			//插入订单物流
			if (updateOM) {
				OrderLogistics lRecord = new OrderLogistics();
				Date now = new Date();
				lRecord.setLogisticsNo(orderDeliverVo.getLogisticsNo())
						.setOrderNo(orderDeliverVo.getOrderNo())
						.setLogisticsEnterpriseCode(orderDeliverVo.getCode())
						.setLogisticsEnterpriseName(orderDeliverVo.getName())
						.setLogisticsBatch(1)   //暂时无分批  默认1
						.setCreateTime(now)
						.setUpdateTime(now);
				orderLogisticsService.save(lRecord);

			}
			if(!updateOM){
				subResult.setBizMessage(ResultCode.CODE_COMMON_ERROR);
				subResult.setBizMessage("更新订单失败，请重新尝试.");
			}
			return subResult;
		} catch(LogisticsException e){
			logger.error("订单无法订阅内部物流消息",e);
			return ResultGenerator.genFailResult("处理物流信息失败，请重新尝试");
		}
	}

	public Result<Void> updateOrderMoney(Long shopID, OrderMain orderMain){
		OrderMain oRecord = new OrderMain();
		oRecord.setTotalAmount(orderMain.getTotalAmount());
		oRecord.setFreight(orderMain.getFreight());
		oRecord.setReceivableAmount(orderMain.getReceivableAmount());
		boolean updateOM = orderMainService.update(oRecord, new QueryWrapper<OrderMain>()
				.eq("order_no", orderMain.getOrderNo())
				.eq("status", OrderDBStatusEnum.CUSTOMER_CONFIRMED_WAITING_FOR_PAYMENT.getCode())
				.eq("del_flag", false));
		Result<Void> subResult = ResultGenerator.genSuccessResult();
		if(!updateOM){
			subResult.setBizMessage(ResultCode.CODE_COMMON_ERROR);
			subResult.setBizMessage("更新订单失败，请重新尝试.");
		}
		return subResult;
	}

    /**
     * 订单拆分,前端传过来N个子订单ID,后端根据子订单ID找到主订单, 复制主订单,修改主订单为新订单
     * @param currShopId
     * @param splitOrderVOS
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
	public Result shopOrderSplit(Long currShopId, List<SplitOrderVO> splitOrderVOS) {
        Result<Void> subResult=null;
        OrderMain oRecord = new OrderMain();
        OrderReceiverInfo orderReceiverInfo=null;
        OrderMain oRecordNew = new OrderMain();
        List<OrderSkuInfo> orderSkuInfoList=null;
        List<OrderSkuPic> orderSkuPicList=null;
        List<String> orderDetailIds=new ArrayList<>();
        for (int i = 0;splitOrderVOS!=null&& i < splitOrderVOS.size(); i++) {
            orderDetailIds.add(splitOrderVOS.get(i).getSkuId());
        }
        String orderNo=splitOrderVOS!=null? splitOrderVOS.get(0).getOrderNo():"";

        List<OrderDetail> orderDetails= orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_no",orderNo).in("sku_id",orderDetailIds));
        List<OrderDetail> orderDetailsOld=orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_no",orderNo));
        if(orderDetails!=null && orderDetails.size()>0){
            if(orderDetails.size()>=orderDetailsOld.size()){
                subResult=ResultGenerator.genFailResult("原订单至少保留一个商品信息");

                return subResult;
            }


            List<Long> skuIds=new ArrayList<>();
            for (int i = 0; i < orderDetails.size(); i++) {
                skuIds.add(orderDetails.get(i).getSkuId());
            }
            oRecord=orderMainService.getById(orderDetails.get(0).getOrderId());
            oRecordNew= Json.decode(Json.encode(oRecord),OrderMain.class);
            oRecordNew.setId(null);
            oRecordNew.setOrderNo(oRecordNew.getOrderNo()+"_"+orderDetails.get(0).getSkuId());
            orderReceiverInfo=orderReceiverInfoService.getOne(new QueryWrapper<OrderReceiverInfo>().eq("order_id",oRecord.getId()));
            orderReceiverInfo.setId(null);
            
            orderSkuInfoList= orderSkuInfoService.list(new QueryWrapper<OrderSkuInfo>().eq("order_id",oRecord.getId()).in("sku_id",skuIds));
            orderSkuPicList= orderSkuPicService.list(new QueryWrapper<OrderSkuPic>().eq("order_id",oRecord.getId()).in("sku_id",skuIds));

            Long totalAmount=0L;
            for (int i = 0;orderDetails!=null && i < orderDetails.size(); i++) {
                totalAmount+= orderDetails.get(i).getTotalAmount();
            }
            oRecordNew.setTotalAmount(totalAmount);
            oRecordNew.setMdseTotalAmount(totalAmount);
            oRecordNew.setCollectedAmount(totalAmount);
            oRecordNew.setReceivableAmount(totalAmount);
            oRecordNew.setCreateTime(new Date());
            oRecordNew.setStatus(5);
            Boolean o= orderMainService.save(oRecordNew);
            for (int i = 0;orderDetails!=null && i < orderDetails.size(); i++) {
                orderDetails.get(i).setOrderId(oRecordNew.getId());
                orderDetails.get(i).setOrderNo(oRecordNew.getOrderNo());
            }

            for (int i = 0;orderSkuInfoList!=null && i < orderSkuInfoList.size(); i++) {
                orderSkuInfoList.get(i).setOrderId(oRecordNew.getId());
                orderSkuInfoList.get(i).setOrderNo(oRecordNew.getOrderNo());
            }
            for (int i = 0;orderSkuPicList!=null && i < orderSkuPicList.size(); i++) {
                orderSkuPicList.get(i).setOrderId(oRecordNew.getId());
                orderSkuPicList.get(i).setOrderNo(oRecordNew.getOrderNo());
            }
            orderReceiverInfo.setOrderId(oRecordNew.getId());
            orderReceiverInfo.setOrderNo(oRecordNew.getOrderNo());
            oRecord.setTotalAmount(oRecord.getTotalAmount()-totalAmount);
            oRecord.setReceivableAmount(oRecord.getReceivableAmount()-totalAmount);
            oRecord.setMdseTotalAmount(oRecord.getMdseTotalAmount()-totalAmount);

            orderMainService.saveOrUpdate(oRecord);//修改原订单信息
            orderDetailService.saveOrUpdateBatch(orderDetails);
            orderSkuInfoService.saveOrUpdateBatch(orderSkuInfoList);
            orderSkuPicService.saveOrUpdateBatch(orderSkuPicList);
            orderReceiverInfoService.save(orderReceiverInfo);//保存收货信息
            subResult=ResultGenerator.genSuccessResult();
        }else{
            subResult=ResultGenerator.genFailResult("请至少选择一个订单商品");
        }

        return subResult;
	}

    /**
     * 订单合并
     * @param currShopId
     * @param splitOrderVOS
     * @return
     */
    public Result shopOrderMergePost(Long currShopId, SplitOrderVO splitOrderVOS) {
        Result<Void> subResult=null;
        OrderMain orderMain=null;
        OrderReceiverInfo orderReceiverInfo=null;
        OrderMain oRecordNew = new OrderMain();
//        List<OrderSkuInfo> orderSkuInfoList=null;
//        List<OrderSkuPic> orderSkuPicList=null;
        List<OrderDetail> orderDetails=null;

        String orderNO=splitOrderVOS.getOrderNo();

        if(orderNO.contains("_")){
            orderMain=orderMainService.getOne(new QueryWrapper<OrderMain>().eq("order_no",orderNO));
            orderNO=orderNO.substring(0,orderNO.indexOf("_"));
            oRecordNew=orderMainService.getOne(new QueryWrapper<OrderMain>().eq("order_no",orderNO));
            orderSkuInfoService.update(new UpdateWrapper<OrderSkuInfo>().set("order_id",oRecordNew.getId()).set("order_no",oRecordNew.getOrderNo()).eq("order_no",orderMain.getOrderNo()));
            orderSkuPicService.update(new UpdateWrapper<OrderSkuPic>().set("order_id",oRecordNew.getId()).set("order_no",oRecordNew.getOrderNo()).eq("order_no",orderMain.getOrderNo()));
            orderReceiverInfo=orderReceiverInfoService.getOne(new QueryWrapper<OrderReceiverInfo>().eq("order_no",orderMain.getOrderNo()));
            orderReceiverInfoService.removeById(orderReceiverInfo.getId());
            orderDetailService.update(new UpdateWrapper<OrderDetail>().set("order_no",oRecordNew.getOrderNo()).set("order_id",oRecordNew.getId()).eq("order_no",orderMain.getOrderNo()));
            orderMain.setReceivableAmount(orderMain.getReceivableAmount()+oRecordNew.getReceivableAmount());
            oRecordNew.setTotalAmount(oRecordNew.getTotalAmount()+orderMain.getTotalAmount());
            oRecordNew.setCollectedAmount(oRecordNew.getCollectedAmount()+orderMain.getCollectedAmount());
            oRecordNew.setMdseTotalAmount(oRecordNew.getMdseTotalAmount()+orderMain.getMdseTotalAmount());

            orderMainService.removeById(orderMain.getId());
            orderMainService.saveOrUpdate(oRecordNew);
            subResult=ResultGenerator.genSuccessResult();
        }else{
            subResult=ResultGenerator.genFailResult("原订单禁止删除");
        }

        return subResult;
    }

    public static void main(String[] args) {
        String ss="asdasdasfw_22";
        System.out.println(ss.substring(0,ss.indexOf("_")));
    }
}
